package com.atguigu.flink.window;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import com.atguigu.flink.utils.MyUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2023/4/7
 *
 *
 *  按照类型： 时间，计数
 *  按照特征:  滚动，滑动，会话
 *  按照计算方式: 全局，keyed窗口(非全局)
 *
 *
 *   滚动的，keyed，计数窗口(size = 3,slide = 3)
 *      每来3条数据，就算一次。
 *      窗口中最多存放3条
 *      不区分key
 *
 * 
 *   WindowedStream: 当前是一个按照key进行分组的窗口流。
 *   只要是WindowedStream，即便下游进行窗口运算的 Task只有一个，也是按照key进行窗口的划分。每种key各有各的窗口，互不干扰。
 *
 *
 *
 *
 *
 *
 */
public class Demo2_CountWindow
{
    public static void main(String[] args) {
        

        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 3333);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        WindowedStream<WaterSensor, String, GlobalWindow> ds = env
            .socketTextStream("hadoop102", 8888)
            .map(new WaterSensorMapFunction())
            .keyBy(WaterSensor::getId)
            // 按照key进行窗口的划分，每种key都有自己的窗口。
            //.countWindow(3);
            .countWindow(2,3);

        ds
           .process(new ProcessWindowFunction<WaterSensor, String, String, GlobalWindow>()
           {
               @Override
               public void process(String key, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                   out.collect(key +":"+ MyUtil.parseToList(elements));
               }
           }).setParallelism(1)
           .print();

        
                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
        
    }
}
